//
// C++ Implementation: gptpart
//
// Description: Class to implement a SINGLE GPT partition
//
//
// Author: Rod Smith <rodsmith@rodsbooks.com>, (C) 2009-2018
//
// Copyright: See COPYING file that comes with this distribution
//
//
// This program is copyright (c) 2009 by Roderick W. Smith. It is distributed
// under the terms of the GNU GPL version 2, as detailed in the COPYING file.

#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS

#include <string.h>
#include <stdio.h>
#include <iostream>
#include "gptpart.h"
#define UnicodeString std::string

using namespace std;

GPTPart::GPTPart(void) {
   partitionType.Zero();
   uniqueGUID.Zero();
   firstLBA = 0;
   lastLBA = 0;
   memset(name, 0, NAME_SIZE * sizeof(name[0]) );
}

GPTPart::GPTPart(const GPTPart & orig) {
   partitionType = orig.partitionType;
   uniqueGUID = orig.uniqueGUID;
   firstLBA = orig.firstLBA;
   lastLBA = orig.lastLBA;
   memcpy(name, orig.name, NAME_SIZE * sizeof( name[ 0 ] ) );
}

GPTPart::~GPTPart(void) {
}

// Return the gdisk-specific two-byte hex code for the partition
uint16_t GPTPart::GetHexType(void) const {
   return partitionType.GetHexType();
}

// Return a plain-text description of the partition type (e.g., "Linux/Windows
// data" or "Linux swap").
string GPTPart::GetTypeName(void) {
   return partitionType.TypeName();
}

// Compute and return the partition's length (or 0 if the end is incorrectly
// set before the beginning).
uint64_t GPTPart::GetLengthLBA(void) const {
   uint64_t length = 0;

   if (firstLBA <= lastLBA)
      length = lastLBA - firstLBA + UINT64_C(1);
   return length;
}

// Return partition's name field, converted to a C++ UTF-8 string
string GPTPart::GetDescription(void) const {
   // convert name to utf32 then to utf8
   string utf8 ;
   size_t pos = 0 ;
   while ( ( pos < NAME_SIZE ) && ( name[ pos ] != 0 ) ) {
      uint16_t cp = name[ pos ++ ] ;
      // first to utf32
      uint32_t uni ;
      if ( cp < 0xd800 || cp > 0xdfff ) {
         uni = cp ;
      }
      else if ( cp < 0xdc00 ) {
         // lead surrogate
         uni = ( (uint32_t)( cp & 0x3ff ) ) << 10 ;
         if ( pos >= NAME_SIZE ) {
            // missing trail surrogate, name[] is invalid
            break ;
         }
         cp = name[ pos ++ ] ;
         if ( cp < 0xdc00 || cp > 0xdfff ) {
            // invalid trail surrogate, name[] is invalid
            break ;
         }
         // trail surrogate
         uni |= cp & 0x3ff ;
         uni += 0x10000 ;
      }
      else {
         // unexpected trail surrogate, name[] is invalid
         break ;
      }
      // then to utf8
      if ( uni < 0x80 ) {
         utf8 += (char) uni ;
      }
      else if ( uni < 0x800 ) {
         utf8 += (char) ( 0xc0 | ( uni >> 6 ) ) ;
         utf8 += (char) ( 0x80 | ( uni & 0x3f ) ) ;
      }
      else if ( uni < 0x10000 ) {
         utf8 += (char) ( 0xe0 | ( uni >> 12 ) ) ;
         utf8 += (char) ( 0x80 | ( ( uni >> 6 ) & 0x3f ) ) ;
         utf8 += (char) ( 0x80 | ( uni & 0x3f ) ) ;
      }
      else {
         utf8 += (char) ( 0xf0 | ( uni >> 18 ) ) ;
         utf8 += (char) ( 0xe0 | ( ( uni >> 12 ) & 0x3f ) ) ;
         utf8 += (char) ( 0x80 | ( ( uni >> 6 ) & 0x3f ) ) ;
         utf8 += (char) ( 0x80 | ( uni & 0x3f ) ) ;
      }
   }
   return utf8 ;
}

// Return 1 if the partition is in use
int GPTPart::IsUsed(void) {
   return (partitionType != GUIDData("0x00"));
}

// Returns MBR_SIZED_GOOD, MBR_SIZED_IFFY, or MBR_SIZED_BAD; see comments
// in header file for details.
int GPTPart::IsSizedForMBR(void) {
   int retval = MBR_SIZED_GOOD;

   if ((firstLBA > UINT32_MAX) || ((lastLBA - firstLBA) > UINT32_MAX) || (firstLBA > lastLBA))
      retval = MBR_SIZED_BAD;
   else if (lastLBA > UINT32_MAX)
      retval = MBR_SIZED_IFFY;

   return (retval);
}

// Set the type code to the specified one. Also changes the partition
// name *IF* the current name is the generic one for the current partition
// type.
void GPTPart::SetType(PartType t) {
   if (GetDescription() == partitionType.TypeName()) {
      SetName(t.TypeName());
   }
   partitionType = t;
}

// Set the name for a partition to theName. Note that theName is a
// standard C++-style ASCII string, although the GUID partition definition
// requires a UTF-16LE string. This function creates a simple-minded copy
// for this.
void GPTPart::SetName(const string & theName) {
   // convert utf8 to utf32 then to utf16le
   size_t len = theName.length() ;
   size_t pos = 0 ;
   for ( size_t i = 0 ; pos < NAME_SIZE && i < len ; ) {
      uint32_t uni ;
      uint8_t cp = theName[ i ++ ] ;
      int todo ;
      if ( cp < 0x80 ) {
         uni = cp ;
         todo = 0 ;
      }
      else if ( cp < 0xc0 || cp > 0xf7 ) {
         // invalid byte, theName is broken
         break ;
      }
      else if ( cp < 0xe0 ) {
         uni = cp & 0x1f ;
         todo = 1 ;
      }
      else if ( cp < 0xf0 ) {
         uni = cp & 0x0f ;
         todo = 2 ;
      }
      else {
         uni = cp & 0x7 ;
         todo = 3 ;
      }
      while ( todo > 0 ) {
         if ( i >= len ) {
            // missing continuation byte, theName is broken
            goto break_converter ;
         }
         cp = theName[ i ++ ] ;
         if ( cp > 0xbf || cp < 0x80 ) {
            // invalid continuation byte, theName is broken
            goto break_converter ;
         }
         uni <<= 6 ;
         uni |= cp & 0x3f ;
         todo -- ;
      }
      // then to utf16le
      if ( uni < 0x10000 ) {
         name[ pos ] = (uint16_t) uni ;
         pos ++ ;
      }
      else {
         if ( pos > NAME_SIZE - 2 ) {
             // not enough room for two surrogates, truncate
             break ;
         }
         uni -= 0x10000 ;
         name[ pos ] = (uint16_t)( uni >> 10 ) | 0xd800 ;
         pos ++ ;
         name[ pos ] = (uint16_t)( uni & 0x3ff ) | 0xdc00 ;
         pos ++ ;
      }
   }
   break_converter : ;
   // finally fill with zeroes
   while ( pos < NAME_SIZE ) {
      name[ pos ++ ] = 0 ;
   }
}

// Set the name for the partition based on the current GUID partition type
// code's associated name
void GPTPart::SetDefaultDescription(void) {
   SetName(partitionType.TypeName());
}

GPTPart & GPTPart::operator=(const GPTPart & orig) {
   partitionType = orig.partitionType;
   uniqueGUID = orig.uniqueGUID;
   firstLBA = orig.firstLBA;
   lastLBA = orig.lastLBA;
   memcpy(name, orig.name, NAME_SIZE * sizeof( name[ 0 ] ) );
   return *this;
}

// Compare the values, and return a bool result.
// Because this is intended for sorting and a firstLBA value of 0 denotes
// a partition that's not in use and so that should be sorted upwards,
// we return the opposite of the usual arithmetic result when either
// firstLBA value is 0.
bool GPTPart::operator<(const GPTPart &other) const {
   if (firstLBA && other.firstLBA)
      return (firstLBA < other.firstLBA);
   else
      return (other.firstLBA < firstLBA);
}

// Blank (delete) a single partition
void GPTPart::BlankPartition(void) {
   uniqueGUID.Zero();
   partitionType.Zero();
   firstLBA = 0;
   lastLBA = 0;
   memset(name, 0, NAME_SIZE * sizeof( name[0]) );
}

// Returns 1 if the two partitions overlap, 0 if they don't
int GPTPart::DoTheyOverlap(const GPTPart & other) {
   // Don't bother checking unless these are defined (both start and end points
   // are 0 for undefined partitions, so just check the start points)
   return firstLBA && other.firstLBA &&
          (firstLBA <= other.lastLBA) != (lastLBA < other.firstLBA);
}

// Reverse the bytes of integral data types and of the UTF-16LE name;
// used on big-endian systems.
void GPTPart::ReversePartBytes(void) {
   ReverseBytes(&firstLBA, 8);
   ReverseBytes(&lastLBA, 8);
   ReverseNameBytes();
}

void GPTPart::ReverseNameBytes(void) {
   int i;

   for (i = 0; i < NAME_SIZE; i ++ )
      ReverseBytes(name + i, 2);
}
